package com.app.brilliant.sys.service.impl;
import com.app.brilliant.shiro.param.SystemRegisterParam;
import com.app.brilliant.shiro.util.SaltUtil;
import com.app.brilliant.sys.bean.SysUser;
import com.app.brilliant.sys.service.SysUserService;
import com.app.brilliant.sys.mapper.SysUserMapper;
import com.app.brilliant.util.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import com.app.brilliant.common.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* @author GF
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2025-07-25 11:51:26
*/
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser>
implements SysUserService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(SystemRegisterParam systemRegisterParam) {
        // 1. 检查用户名是否已存在
        String username = systemRegisterParam.getUsername();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 2. 创建用户对象
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setNickname(username); // 默认昵称与用户名相同
        
        // 3. 生成盐值并加密密码
        String salt = SaltUtil.generateSalt();
        String password = PasswordUtil.encrypt(systemRegisterParam.getPassword(), salt);
        
        // 4. 设置用户信息
        sysUser.setSalt(salt);
        sysUser.setPassword(password);
        sysUser.setState(1); // 1: 启用
        sysUser.setDeleted(0); // 0: 未删除
        sysUser.setGender(1); // 默认为男性
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        
        // 5. 保存用户
        this.save(sysUser);
    }
}
